package com.zagj.videocomparess;

import android.media.AudioFormat;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.Surface;


import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Created by Chen qin lang on 2018/4/8.
 */

public class CameraDecode {
    public String audioMime = MediaFormat.MIMETYPE_AUDIO_AAC;
    public int sampleRate = 256000;
    public int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
    public int channelCount = 2;
    public int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

    public String videoMime = MediaFormat.MIMETYPE_VIDEO_AVC;
    public int frameRate = 24;
    public int frameInterval = 1;
    public int color = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible;
    public int fpsTime;
    public String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator;
    private MediaExtractor mediaExtractor;
    private MediaCodec mediaCodec;
    private MediaCodec videoCodec;
    private Surface surface;
    private ByteBuffer outputBuffer;
    private boolean startFlags;
    private PlayerThread playerThread;

    public CameraDecode() {
        fpsTime = 1000 / frameRate;

    }
    public void  stop(){
        try{
            startFlags=false;
            playerThread.join();
            mediaExtractor.release();

        }catch (Exception e){

        }
    }
    public void prepare(Surface surface) {
        this.surface = surface;
        try {
            mediaExtractor = new MediaExtractor();
            mediaExtractor.setDataSource(path + "121233.mp4");
            if (playerThread != null && playerThread.isAlive()) {
                startFlags = false;
                playerThread.join();
            }
            startFlags = true;
            playerThread = new PlayerThread();
            playerThread.start();

      /*      MediaFormat videoformat =MediaFormat.createVideoFormat(videoMime,width,height);
            videoformat.setInteger(MediaFormat.KEY_BIT_RATE,sampleRate);
            mediaCodec = MediaCodec.createDecoderByType(videoMime);
            mediaCodec.configure(videoformat,surface,null,0);*/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class PlayerThread extends Thread {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void run() {
            super.run();
            try {
                for (int i = 0; i < mediaExtractor.getTrackCount(); i++) {
                    MediaFormat trackFormat = mediaExtractor.getTrackFormat(i);
                    String mime = trackFormat.getString(MediaFormat.KEY_MIME);
                    if (mime.startsWith("video/")) {
                        mediaExtractor.selectTrack(i);
                        videoCodec = MediaCodec.createDecoderByType(mime);
                        videoCodec.configure(trackFormat, surface, null, 0);
                    }
                }

                if (videoCodec != null) {
                    while (startFlags) {


                        int index = videoCodec.dequeueInputBuffer(-1);
                        if (index >= 0) {
                            ByteBuffer inputBuffer = videoCodec.getInputBuffer(index);
                            inputBuffer.clear();
                            int length = mediaExtractor.readSampleData(inputBuffer, 0);
                            if (length > 0) {
                                videoCodec.queueInputBuffer(index, 0, length, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                            }
                        }

                        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
                        int outindex = videoCodec.dequeueOutputBuffer(bufferInfo, 0);
                        if (outindex >= 0) {
                            switch (outindex) {
                                case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
                                    //格式改变
                                    outputBuffer = videoCodec.getOutputBuffer(outindex);
                                    break;
                                case MediaCodec.BUFFER_FLAG_CODEC_CONFIG:
                                    //开始截断
                                    break;
                                case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
                                    //结束
                                    break;
                                default:
                                    outindex = videoCodec.dequeueOutputBuffer(bufferInfo, 0);
                                    if (bufferInfo.flags == MediaCodec.BUFFER_FLAG_CODEC_CONFIG) {
                                        //编码头信息
                                    } else if (bufferInfo.flags % 8 == mediaCodec.BUFFER_FLAG_KEY_FRAME) {
                                        //关键帧
                                    }
                                    break;
                            }
                        }
                    }

                    mediaCodec.stop();
                    mediaCodec.release();
                    mediaExtractor.release();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
